<template>
  <div class="box">
    <div id="echarts-box"></div>
    <div id="keys-box"></div>
  </div>
</template>

<script setup  lang="ts">
import * as echarts from 'echarts';
import { onMounted, reactive } from "vue"
import { getEchartsApi } from '@/api/echarts';


let xData: String[] = reactive([])
let seriesData: number[] = reactive([])
var myChart
var chartDom

// 获取数据
const getData = (cb) => {
  getEchartsApi().then((res: any) => {
    if (res.data.code === '200') {
      res.data.data.forEach(item => {
        xData.push(item.x)
        seriesData.push(item.val)
      })
      cb && cb()
    }
  })
}


function getBar() {
  myChart = echarts.init(document.getElementById('echarts-box'));
  myChart.setOption({
    title: {
      text: '嗨购周销量统计柱状图'
    },
    tooltip: {},
    xAxis: {
      data: xData
    },
    yAxis: {},
    series: [
      {
        name: '销量',
        type: 'bar',
        data: seriesData
      }
    ]
  });
}


function getkeys() {
  chartDom = document.getElementById('keys-box');
  myChart = echarts.init(chartDom);
  var option;

  const colors = ['#5470C6', '#EE6666'];
  option = {
    color: colors,
    tooltip: {
      trigger: 'none',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {},
    grid: {
      top: 70,
      bottom: 50
    },
    xAxis: [
      {
        type: 'category',
        axisTick: {
          alignWithLabel: true
        },
        axisLine: {
          onZero: false,
          lineStyle: {
            color: colors[1]
          }
        },
        axisPointer: {
          label: {
            formatter: function (params) {
              return (
                'Precipitation  ' +
                params.value +
                (params.seriesData.length ? '：' + params.seriesData[0].data : '')
              );
            }
          }
        },
        data: xData
      },
      {
        type: 'category',
        axisTick: {
          alignWithLabel: true
        },
        axisLine: {
          onZero: false,
          lineStyle: {
            color: colors[0]
          }
        },
        axisPointer: {
          label: {
            formatter: function (params) {
              return (
                'Precipitation  ' +
                params.value +
                (params.seriesData.length ? '：' + params.seriesData[0].data : '')
              );
            }
          }
        }
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [
      {
        name: '嗨购周销量统计折线图',
        type: 'line',
        emphasis: {
          focus: 'series'
        },
        data: seriesData
      }
    ]
  };

  option && myChart.setOption(option);
}

onMounted(() => {
  getData(getBar)

  getData(getkeys)

})

</script>

<style scoped>
.box {
  display: flex;
  justify-content: space-around;
}

#echarts-box {
  width: 600px;
  height: 400px;
}

#keys-box {
  width: 600px;
  height: 400px;
}
</style>